package com.abe.bathsystem.utils;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

import com.abe.bathsystem.android.ResetActivity;
import com.abe.bathsystem.base.ManagerLocalData;
import com.abe.libcore.utils.Utils;
import com.abe.libcore.utils.normal.CommonUtils;
import com.abe.libcore.utils.normal.ConstantCore;
import com.maning.mndialoglibrary.MProgressDialog;
import com.maning.mndialoglibrary.config.MDialogConfig;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.NetworkInterface;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class NormalUtils {
    public interface OnGetNetTimeListener {
        void onGetNetTime(Date date);
    }

    public static void getNetTime(OnGetNetTimeListener listener) {
        Date date;
        String webUrl = "http://www.ntsc.ac.cn";//中国科学院国家授时中心
        try {
            URL url = new URL(webUrl);
            URLConnection uc = url.openConnection();
            uc.setReadTimeout(5000);
            uc.setConnectTimeout(5000);
            uc.connect();
            long correctTime = uc.getDate();
            date = new Date(correctTime);
        } catch (Exception e) {
            date = new Date();
        }
        if (listener != null) {
            listener.onGetNetTime(date);
        }
    }

    public static float getScale() {
        DisplayMetrics displayMetrics = Utils.getContext().getResources().getDisplayMetrics();
        float width = displayMetrics.widthPixels;
        return width / getDesignWidth();
    }

    private static float getDesignWidth() {
        DisplayMetrics displayMetrics = Utils.getContext().getResources().getDisplayMetrics();
        float width = displayMetrics.widthPixels;
        int DesignWidth = CommonUtils.getMetaIntData(Utils.getContext(), ConstantBath.META_DATA_DESIGN_WIDTH);
        if (DesignWidth == 0) return width;
        return DesignWidth;
    }

    /*
     * 服务请求弹窗
     * */
    public static void showRequestDialog(Context context) {

        //自定义背景
        MDialogConfig mDialogConfig = new MDialogConfig.Builder()
                //点击外部是否可以取消
                .isCanceledOnTouchOutside(false)
                //View背景的圆角
                .setCornerRadius(20)
                //View 边框的宽度
                .setStrokeWidth(2)
                //Progress 颜色
                .setProgressColor(Color.WHITE)
                //Progress 宽度
                .setProgressWidth(3)
                //Progress 内圈宽度
                .setProgressRimWidth(4)
                //文字的颜色
                .setTextColor(Color.WHITE)
                //ProgressBar 颜色
                .setProgressColor(Color.WHITE)
                //文字的大小：sp
                .setTextSize(15)
                //padding
                .setPadding(40, 10, 40, 10)
                .build();
        MProgressDialog.showProgress(context, "开启洗浴服务请求中...", mDialogConfig);
    }

    /**
     * 获取Android下所有应用
     */
    public static List<ResolveInfo> loadApps() {
        List<ResolveInfo> showApps, needApps;
        needApps = new ArrayList<>();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        showApps = Utils.getContext().getPackageManager()
                .queryIntentActivities(mainIntent, 0);
        //* 去掉自己 */
        String selfPackageName = Utils.getContext().getPackageName();
        for (int i = 0; i < showApps.size(); i++) {
            ResolveInfo resolveInfo = showApps.get(i);
            String tempPackage = resolveInfo.activityInfo.packageName;
            if (!selfPackageName.equals(tempPackage)) {
                needApps.add(resolveInfo);
            }
        }
        return needApps;
    }

    public static ResolveInfo loadSelf() {
        List<ResolveInfo> showApps;
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        showApps = Utils.getContext().getPackageManager()
                .queryIntentActivities(mainIntent, 0);
        ResolveInfo self = null;
        String selfPackageName = Utils.getContext().getPackageName();
        for (int i = 0; i < showApps.size(); i++) {
            ResolveInfo resolveInfo = showApps.get(i);
            String tempPackage = resolveInfo.activityInfo.packageName;
            if (selfPackageName.equals(tempPackage)) {
                self = resolveInfo;
                break;
            }
        }
        return self;
    }

    //安装APK
    public static boolean installAPK(String apkPath) {
        ManagerLocalData.updateAPP(true);
        if (TextUtils.isEmpty(apkPath)) {
            return false;
        }
        File file = new File(apkPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= 24) {
            //provider authorities
            Uri apkUri = FileProvider.getUriForFile(Utils.getContext(), getPkgName(), file);
            //Granting Temporary Permissions to a URI
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        Utils.getContext().startActivity(intent);
        return true;
    }

    //获取包名
    public static String getPkgName() {
        return Utils.getContext().getPackageName();
    }

    //获取包管理
    private static PackageManager getPackageManager() {
        return Utils.getContext().getPackageManager();
    }

    // 获取版本号
    public static int getVersionCode() {
        int versionCode = 0;
        try {
            versionCode = getPackageManager().getPackageInfo(
                    getPkgName(), 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    //获取版本号名称
    public static String getVersionName() {
        String versionName = "";
        try {
            versionName = getPackageManager().getPackageInfo(
                    getPkgName(), 0).versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    public static void resetApp() {
        resetApp(ResetActivity.class);
    }

    /**
     * 重启APP
     *
     * @param cls 制定重启路径
     */
    private static void resetApp(Class<?> cls) {
        Intent mStartActivity = new Intent(Utils.getContext(), cls);
        int mPendingIntentId = 123456;
        PendingIntent mPendingIntent = PendingIntent.getActivity(Utils.getContext(), mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager mgr = (AlarmManager) Utils.getContext().getSystemService(Context.ALARM_SERVICE);
        if (mgr == null) return;
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
        System.exit(0);
    }

    public static String getString(int id) {
        return Utils.getContext().getResources().getString(id);
    }

    public static boolean saveFileInfo(String path, String data) {
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                File dir = new File(ConstantCore.CORE_PATH);
                if (!dir.exists()) {
                    boolean isSuccess = dir.mkdirs();
                    System.out.println(isSuccess);
                }
                FileOutputStream fos = new FileOutputStream(path);
                fos.write(data.getBytes());
                fos.close();
            }
            return true;
        } catch (Exception e) {
            Log.e("", "an error occured while writing file...", e);
        }
        return false;
    }

    public static String getFileInfo(String path) {
        try {
            FileInputStream inputStream = new FileInputStream(path);
            byte temp[] = new byte[1024];
            StringBuilder sb = new StringBuilder("");
            int len = 0;
            while ((len = inputStream.read(temp)) > 0) {
                sb.append(new String(temp, 0, len));
            }
            inputStream.close();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //获取设备MAC地址
    public static String getMac(Context context, boolean isTest) {
        String mac;
        if (isTest) {
            return "CC:B8:A8:32:3C:F8";
        }
        try {
            NetworkInterface networkInterface = NetworkInterface.getByName("wlan0");
            byte[] addrByte = networkInterface.getHardwareAddress();
            StringBuilder sb = new StringBuilder();
            for (byte b : addrByte) {
                sb.append(String.format("%02X:", b));
            }
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            mac = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            WifiManager wifiM = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            try {
                WifiInfo wifiI = wifiM.getConnectionInfo();
                mac = wifiI.getMacAddress();
            } catch (NullPointerException e1) {
                e1.printStackTrace();
                mac = "02:00:00:00:00:00";
            }
        }
        System.out.print("MAC:" + mac);
        return mac;
    }

    public static boolean randomBool() {
        int min = 1;
        int max = 100;
        Random random = new Random();
        int num = random.nextInt(max) % (max - min + 1) + min;
        return num > 50;
    }

    /**
     * 设置隐藏标题栏
     *
     * @param activity activity_setting
     */
    public static void setNoTitleBar(Activity activity) {
        activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    /**
     * 设置全屏
     *
     * @param activity activity_setting
     */
    public static void setFullScreen(Activity activity) {
        activity.getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 取消全屏
     *
     * @param activity activity_setting
     */
    public static void cancelFullScreen(Activity activity) {
        activity.getWindow().clearFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
}